package tool;

import java.awt.Color;
import java.sql.Timestamp;
import java.util.*;

import com.base.bean.*;


/**
 * 图片处理类：
 * 通过mediaId下载图片  打水印  重命名文件名
 * 
 * tempPath：临时文件存放地
 * localPath：本地文件存放地
 * 
 * @author Administrator
 *
 */
public class ImageTool {
	
	
	// 单例模式 start
	private volatile static ImageTool instance = null;
	private static String tempPath;
	private static String localPath;
	
	private static String _url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
	
	
	private ImageTool() {
		this.localPath=SysArgsTool.getSysArgs().getSysArgs().get("imgLocalPath");
		this.tempPath=SysArgsTool.getSysArgs().getSysArgs().get("imgTempPath");
	}
	
	public static ImageTool getInstance() {
		if (instance == null) {
			synchronized (ImageTool.class) {// 1
				if (instance == null) {// 2
					instance = new ImageTool();// 3
				}
			}
		}
		return instance;
	}
	// 单例模式 end
	
	
	/**
	 * @param subPath   eg:2015/2
	 * 新增按年月  文件夹
	 * @return Image:just define fileName;
	 */
	public static synchronized Image download(Integer creator,String mediaId,String accessToken,String subPath){
		
		
		Image image=new Image();
		String url=_url.replace("ACCESS_TOKEN", accessToken);
		url=url.replace("MEDIA_ID", mediaId);
		
//		System.out.println("############################");
//		System.out.println(url);
		
		try{
		DownImg.download(url, mediaId+".jpg", tempPath+"/"+subPath);
		image.setState(0);		//表示已经将mediaId对应的图片下载到本地
		image.setPath(subPath);
		image.setMediaId(mediaId);
		image.setFileName(mediaId+".jpg");
		image.setCreator(creator);
		
		return image;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	
	
	
	
	public static synchronized Image markAndMove(Integer creator,Image image,String content){

		Timestamp current = TimeTool.getCurrentTime();
		creator=(creator==null?0:creator);
			
		String fileName=creator.toString()+"_"+new Long(System.currentTimeMillis()).toString()+"_"+StringTool.getRandom(4)+".jpg";
		
		image.setCreated(current);
		image.setDiscription(content);
		
		String timeStr=TimeTool.getNowTime()+"  "+TimeTool.getWeekDay();
		WaterMarkUtils.getInstance().mark(tempPath+"/"+image.getPath()+"/"+image.getFileName(), localPath+"/"+image.getPath()+"/"+fileName, Color.red, content,timeStr);
		
		image.setFileName(fileName);
		image.setState(1);		//重命名水印后的文件到本地路径
		return image;
	}
	
	
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
